import TIM from 'tim-wx-sdk';
import TIMUploadPlugin from 'tim-upload-plugin';

let app = getApp();

let options = {
  SDKAppID: app.globalData.SDKAppID // SDKAppID
};
let tim = TIM.create(options);

let onMessageReceived = function (event) {
  let pages = getCurrentPages();
  let page = pages[pages.length - 1];
  page.setData({
    hasMessage: true
  })
};

Page({

  data: {
    nickname: '',
    avatarUrl: '',
    phone: '请完善个人信息',
    records: [],
    hasMessage: false,
  },

  onLoad() {
    let userInfo = wx.getStorageSync('userInfo');

    //昵称和头像
    this.setData({
      nickname: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl
    })

    let userId = wx.getStorageSync('userId');

    //手机
    wx.request({
      url: app.globalData.prefix+'/visitor/getVisitorById/' + userId,
      success: (res) => {
        if (res.data.data.userInfo.userPhone != null) {
          this.setData({
            phone: res.data.data.userInfo.userPhone,
          })
        }
      }
    })

    wx.showLoading({
      title: '加载中',
    })
    //咨询记录
    wx.request({
      url: app.globalData.prefix+'/record/getConsultRecordsByVisitorId/' + userId,
      success: (res) => {
        console.log(res);
        //按日期降序排列
        res.data.data.sort(function (r1, r2) {
          let time1 = new Date(r1.recordInfo.datetime.replace(/-/g, "/")).getTime();
          let time2 = new Date(r2.recordInfo.datetime.replace(/-/g, "/")).getTime();
          return time2 - time1;
        })
        //只展示未评价的那些咨询记录，并且需要把duration转换为xx小时xx分钟的形式
        //并且要把当前进行中的去除
        let result = [];
        for (let i = 0; i < res.data.data.length; i++) {
          let record = res.data.data[i];
          if (record.recordInfo.fromGrade === null && !(record.recordInfo.consultRecordId == wx.getStorageSync('rid')) && record.recordInfo.duration !== null) {
            let minute = record.recordInfo.duration;
            let hour = 0;
            while (minute >= 60) {
              hour++;
              minute -= 60;
            }
            record.recordInfo.duration = hour + "小时" + minute + "分钟";
            result.push(record);
          }
        }
        this.setData({
          records: result
        })
        wx.hideLoading();
      }
    })
  },

  onShow() {
    //判断目前是否有来自当前咨询师的未读的消息
    let ongoingId = wx.getStorageSync('ongoingId');
    if (!(ongoingId === null || ongoingId === undefined || ongoingId === '')) {
      let conversationId = "C2C" + ongoingId;
      let promise = tim.getConversationList([conversationId]);
      let that = this;
      promise.then(function (imResponse) {
        const conversation = imResponse.data.conversationList[0];
        console.log(conversation);
        if (conversation.unreadCount > 0) {
          that.setData({
            hasMessage: true
          })
        } else {
          that.setData({
            hasMessage: false
          })
        }
      }).catch(function (imError) {
        console.warn('getConversationList error:', imError);
      });
    }
    //开始监听有无新消息
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },

  onHide() {
    //只要不在当前页面就不监听
    tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },

  goImprove() {
    wx.navigateTo({
      url: '../modify/modify'
    })
  },


  goAgree() {
    wx.switchTab({
      url: '../agreeBook/agreeBook',
    })
  },

  handleChoose(e) {
    let cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '../chat/chat?cid=' + cid,
    })
  }


})